/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication0;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author user1
 */
public class Graphical extends javax.swing.JFrame {
    
    private static final int FILE_OPEN_DOMAIN = 1;
    private static final int FILE_OPEN_PROBLEM = 2;
    private static final int FILE_SAVE_DOMAIN = 3;
    private static final int FILE_SAVE_PROBLEM = 4;
    private boolean changed = false ;
    /**
     * Creates new form Graphical
     */
    public Graphical() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        ProblemFileTxt = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        DomainFileTxt = new javax.swing.JTextArea();
        GetTypes = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        listOfTypes = new javax.swing.JList();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        New = new javax.swing.JMenuItem();
        OpenDomainFile = new javax.swing.JMenuItem();
        OpenProblemFile = new javax.swing.JMenuItem();
        SaveDomainFile = new javax.swing.JMenuItem();
        SaveProblemFile = new javax.swing.JMenuItem();
        Exit = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        ProblemFileTxt.setColumns(20);
        ProblemFileTxt.setRows(5);
        ProblemFileTxt.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                ProblemFileTxtKeyTyped(evt);
            }
        });
        jScrollPane1.setViewportView(ProblemFileTxt);

        jLabel1.setText("Domain File :");

        jLabel2.setText("Problem File :");

        DomainFileTxt.setColumns(20);
        DomainFileTxt.setRows(5);
        DomainFileTxt.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                DomainFileTxtKeyTyped(evt);
            }
        });
        jScrollPane2.setViewportView(DomainFileTxt);

        GetTypes.setText("Get types");
        GetTypes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                GetTypesActionPerformed(evt);
            }
        });

        jScrollPane3.setToolTipText("");

        listOfTypes.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "space", "fule", "location", "venical", "cargo" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        listOfTypes.addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
                listOfTypesAncestorAdded(evt);
            }
            public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
            }
        });
        jScrollPane3.setViewportView(listOfTypes);

        jMenu1.setText("File");
        jMenu1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu1ActionPerformed(evt);
            }
        });

        New.setText("New");
        New.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NewActionPerformed(evt);
            }
        });
        jMenu1.add(New);

        OpenDomainFile.setText("Open Domain File");
        OpenDomainFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OpenDomainFileActionPerformed(evt);
            }
        });
        jMenu1.add(OpenDomainFile);

        OpenProblemFile.setText("Open Problem File");
        OpenProblemFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OpenProblemFileActionPerformed(evt);
            }
        });
        jMenu1.add(OpenProblemFile);

        SaveDomainFile.setText("Save Domain File");
        SaveDomainFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveDomainFileActionPerformed(evt);
            }
        });
        jMenu1.add(SaveDomainFile);

        SaveProblemFile.setText("Save Problem File");
        SaveProblemFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveProblemFileActionPerformed(evt);
            }
        });
        jMenu1.add(SaveProblemFile);

        Exit.setText("Exit");
        Exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExitActionPerformed(evt);
            }
        });
        jMenu1.add(Exit);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addGap(47, 47, 47)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(GetTypes)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(233, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(3, 3, 3)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(GetTypes))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(31, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void OpenDomainFileActionPerformed(java.awt.event.ActionEvent evt) {                                               
          operateFile("Open Domain File" , FILE_OPEN_DOMAIN);
    }                                              

    private void NewActionPerformed(java.awt.event.ActionEvent evt) {                                    
        if(changed){
            int result = JOptionPane.showConfirmDialog(null, "Do you want to save this file ?");
            if(result == JOptionPane.YES_OPTION){
                operateFile("save the domain file" , FILE_SAVE_DOMAIN );
                operateFile("save the problem file" , FILE_SAVE_PROBLEM );
            }
            if (result == JOptionPane.CANCEL_OPTION){
            return;}
        }
        
        DomainFileTxt.setText("");
        ProblemFileTxt.setText("");
        
    }                                   

    private void OpenProblemFileActionPerformed(java.awt.event.ActionEvent evt) {                                                
          operateFile("Open Problem File" , FILE_OPEN_PROBLEM);
    }                                               

    private void SaveDomainFileActionPerformed(java.awt.event.ActionEvent evt) {                                               
          operateFile("Save Domain File" , FILE_SAVE_DOMAIN);
    }                                              

    private void ExitActionPerformed(java.awt.event.ActionEvent evt) {                                     
        
        System.exit(0);
    }                                    

    private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
    }                                      

    private void SaveProblemFileActionPerformed(java.awt.event.ActionEvent evt) {                                                
        operateFile("Save PROBLEM File" , FILE_SAVE_PROBLEM);
    }                                               

    private void DomainFileTxtKeyTyped(java.awt.event.KeyEvent evt) {                                       
        changed = true;
    }                                      

    private void ProblemFileTxtKeyTyped(java.awt.event.KeyEvent evt) {                                        
        changed = true;
    }                                       

    private void GetTypesActionPerformed(java.awt.event.ActionEvent evt) {                                         
        
        String s = DomainFileTxt.getText();
        String[] tokens = s.split("\\s+|-");
        for(int i = 0 ; i<tokens.length ; i++ ){
            if(tokens[i]== "types"){
                i++;
                while(tokens[i]!=")"){
                    System.out.println(tokens[i]);
                    i++;
                }
                break;
            }
        }
        
        
        
        
        
        
        
    }                                        

    private void listOfTypesAncestorAdded(javax.swing.event.AncestorEvent evt) {                                          
        String s = (String) listOfTypes.getSelectedValue();
    }                                         

    
    private void operateFile(String title , int type){
        JFileChooser chooser = new JFileChooser();
        int choose = -1;
        chooser.setDialogTitle(title);
        switch (type) {
            case FILE_OPEN_DOMAIN :
                choose = chooser.showOpenDialog(null);
                break;
            case FILE_OPEN_PROBLEM :
                choose = chooser.showOpenDialog(null);
                break;
            case FILE_SAVE_DOMAIN :
                choose = chooser.showSaveDialog(null);
                break;
            case FILE_SAVE_PROBLEM:
                choose = chooser.showSaveDialog(null);
                break;
        }
        
        if(choose == JFileChooser.APPROVE_OPTION){
            File file = chooser.getSelectedFile();
            switch (type) {
            case FILE_OPEN_DOMAIN :
                readDomainFile(file);
                break;
            case FILE_OPEN_PROBLEM :
                readProblemFile(file);
                break;
            case FILE_SAVE_DOMAIN :
                writeDomainFile(file);
                break;
            case FILE_SAVE_PROBLEM:
                writeProblemFile(file);
                break;
        }
        }
    }
    private void readDomainFile(File file){  //open file
        try{
            DomainFileTxt.setText("");
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader (fr);
            String line ;
            while((line =br.readLine()) != null){
                DomainFileTxt.append(line + "\n");
            }
            br.close();
            fr.close();
        }catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Error to open fle : " + e.toString(), "Error" , JOptionPane.ERROR_MESSAGE);
        }
        
    }
    private void readProblemFile(File file){  // open file
         try{
            ProblemFileTxt.setText("");
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader (fr);
            String line ;
            while((line =br.readLine()) != null){
                ProblemFileTxt.append(line + "\n");
            }
            br.close();
            fr.close();
        }catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Error to open fle : " + e.toString(), "Error" , JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void writeDomainFile(File file){ // save file
        try{
            file.createNewFile();
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            String data = DomainFileTxt.getText();
            bw.write(data);
            bw.close();
            fw.close();
            readDomainFile(file);
        }catch (Exception e){
            JOptionPane.showMessageDialog(null, "Error to open fle : " + e.toString(), "Error" , JOptionPane.ERROR_MESSAGE);
        }
    }
    private void writeProblemFile(File file){  // save file
        try{
            file.createNewFile();
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            String data = ProblemFileTxt.getText();
            bw.write(data);
            bw.close();
            fw.close();
            readProblemFile(file);
        }catch (Exception e){
            JOptionPane.showMessageDialog(null, "Error to open fle : " + e.toString(), "Error" , JOptionPane.ERROR_MESSAGE);
        }
    }
    
   
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Graphical.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Graphical.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Graphical.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Graphical.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Graphical().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JTextArea DomainFileTxt;
    private javax.swing.JMenuItem Exit;
    private javax.swing.JButton GetTypes;
    private javax.swing.JMenuItem New;
    private javax.swing.JMenuItem OpenDomainFile;
    private javax.swing.JMenuItem OpenProblemFile;
    private javax.swing.JTextArea ProblemFileTxt;
    private javax.swing.JMenuItem SaveDomainFile;
    private javax.swing.JMenuItem SaveProblemFile;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JList listOfTypes;
    // End of variables declaration                   
}

